import pymysql

from utils.log_util import logger
from utils.read import base_data

data = base_data.read_ini()['mysql']
DB_CONF = {
    "host": data['MYSQL_HOST'],
    "port": int(data['MYSQL_PORT']),
    "user": data['MYSQL_USER'],
    "password": data['MYSQL_PASSWD'],
    "db": data['MYSQL_DB']
}

class MysqlDB:
    def __init__(self):
        #mysql创建连接
        self.conn = pymysql.connect(**DB_CONF, autocommit=True)
        #创建游标
        self.cur = self.conn.cursor(cursor = pymysql.cursors.DictCursor)
        """
        在默认情况下cursor方法返回的是BaseCursor类型对象，BaseCursor类型对象在执行查询后每条记录的结果以列表(list)表示。
如果要返回字典(dict)表示的记录，就要设置cursor参数为pymysql.cursors.DictCursor类。
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        """

    #释放资源
    def __del__(self):
        self.cur.close()
        self.conn.close()

    #查询一条
    def select_db_one(self,sql):
        self.cur.execute(sql)
        result = self.cur.fetchone()
        logger.info(f"执行sql:{sql},执行结果:{result}")
        #获取数据
        return result
    # 查询多条/所有条
    def select_db_all(self,sql):
        self.cur.execute(sql)
        result = self.cur.fetchall()
        logger.info(f"执行sql:{sql},执行结果:{result}")
        #获取数据
        return result

    def execute_db(self,sql):
        #这个方法用来删除数据
        try:
            logger.info(f"执行sql:{sql}")
            self.cur.execute(sql)
            self.conn.commit()
        except Exception as e:
            logger.info("执行SQL出错{}".format(e))

db = MysqlDB()
if __name__ == '__main__':
    db = MysqlDB()
    result = db.select_db_one("select code from users_verifycode where mobile = '15900984857' order by id desc limit 1;")
    print(result)
    print(result['code'])
    